package com.hmy.finance.manager.workflow;

import com.alibaba.fastjson.JSON;
import com.hmy.ccp.common.result.FeignResult;
import com.hmy.ccp.error.exception.HMYRuntimeException;
import com.hmy.workflow.api.bo.request.task.ApprovalTaskRequest;
import com.hmy.workflow.api.bo.response.task.ApprovalTaskResponse;
import com.hmy.workflow.api.client.task.FlowTaskClient;
import java.util.Objects;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class FlowTaskClientManager {

    @Resource
    private FlowTaskClient flowTaskClient;

    /**
     * 审批流程
     *
     * @param approvalTaskRequest approvalTaskRequest
     * @return
     */
    public ApprovalTaskResponse complete(ApprovalTaskRequest approvalTaskRequest) {
        log.info("flowTaskClient#complete param is:{}", JSON.toJSONString(approvalTaskRequest));
        if (StringUtils.isEmpty(approvalTaskRequest.getComment())) {
            approvalTaskRequest.setComment("通过");
        }
        FeignResult<ApprovalTaskResponse> result;
        try{
            result = flowTaskClient.complete(approvalTaskRequest);
        }catch (Exception e){
            throw new HMYRuntimeException(506900001);
        }
        if (Objects.isNull(result)) {
            log.error("flowTaskClient#complete is null");
            throw new HMYRuntimeException("flowProcessClient#start result is null");
        }
        log.info("flowTaskClient#complete result is:{}", JSON.toJSONString(result));
        if (result.isFailed()) {
            throw new HMYRuntimeException(result.getMsgCode(), result.getErrorText());
        }
        if (Boolean.FALSE.equals(result.getData().getSuccess())) {
            throw new HMYRuntimeException(506900001);
        }

        return result.getData();
    }


}
